package com.zb.wx.utils;

import com.zb.wx.WxSecretKeyConstant;
import lombok.extern.log4j.Log4j2;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * 微信加密解密工具类
 * @Author WEN
 * @Date 2024/2/29 0029
 **/
@Log4j2
public class WxSecureUtil {

    /**
     * 数据解密
     * @param request
     * @param xmlData 微信Xml数据
     * @return
     */
    public static String decrypt(HttpServletRequest request, String xmlData) {
        Map<String, String[]> parameterMap = request.getParameterMap();
        String timestamp = parameterMap.get("timestamp")[0];
        String nonce = parameterMap.get("nonce")[0];
        String msgSignature = parameterMap.get("msg_signature")[0];
        // 微信解密对象
        String decryptXml = null;
        try {
            WXBizMsgCrypt wxBizMsgCrypt = new WXBizMsgCrypt(WxSecretKeyConstant.TOKEN, WxSecretKeyConstant.ENCODING_AES_KEY, WxSecretKeyConstant.APP_ID);
            decryptXml = wxBizMsgCrypt.decryptMsg(msgSignature, timestamp, nonce, xmlData);
        } catch (Exception e) {
            log.error("微信Xml数据解密异常：" + e);
            e.printStackTrace();
        }
        return decryptXml;
    }

}
